<template>
  <div id="app-container" class="app-container">
    <!-- 条件搜索 -->
    <div class="filter-container">
      <el-form ref="queryForm" :model="listQuery.param" size="small" :inline="true" label-width="auto">
        <el-form-item label="流程定义" prop="key">
          <flow-proc-key v-model="listQuery.param.key" placeholder="流程定义" style="width: 100%;" class="filter-item" @change="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="流程定义ID" prop="id">
          <el-input v-model="listQuery.param.id" placeholder="流程定义ID" style="width: 300px;" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="listQuery.param.name" placeholder="名称" class="filter-item" @keyup.enter.native="handleFilterQuery" />
        </el-form-item>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" style="margin-left: 10px;" @click="handleFilterQuery">
          搜索
        </el-button>
        <el-button v-waves class="filter-item" icon="el-icon-refresh-right" @click="handleRestQuery">
          重置
        </el-button>
      </el-form>
    </div>
    <div class="filter-container">
      <div style="float: left;">
        <!--        <el-button v-permission="permission.add" class="filter-item" type="primary" plain icon="el-icon-plus" @click="handleCreate">-->
        <!--          新增-->
        <!--        </el-button>-->
        <el-button v-permission="permission.add" class="filter-item" type="primary" plain icon="el-icon-upload" @click="upload = true">
          上传
        </el-button>
      </div>
      <div style="float: right;">
        <el-button icon="el-icon-refresh" circle @click="handleFilterQuery" />
      </div>
    </div>

    <!-- 数据表格 -->
    <el-table
      :key="tableKey"
      v-loading="loading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      scrollbar-always-on="true"
    >
      <el-table-column type="selection" width="50px" align="center" />
      <el-table-column label="序号" type="index" width="50px" align="center" />
      <el-table-column label="流程定义ID" min-width="280px" align="left">
        <template v-slot="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="流程定义KEY" min-width="160px" align="left">
        <template v-slot="{row}">
          <span>{{ row.key }}</span>
        </template>
      </el-table-column>
      <el-table-column label="类别" min-width="200px" align="left">
        <template v-slot="{row}">
          <span>{{ row.category }}</span>
        </template>
      </el-table-column>
      <el-table-column label="名称" min-width="150px" align="left">
        <template v-slot="{row}">
          <span>{{ row.name }}</span>
        </template>
      </el-table-column>
      <el-table-column label="资源文件" min-width="220px" align="left">
        <template v-slot="{row}">
          <el-link @click="handleXml(row)">{{ row.resource }}</el-link>
        </template>
      </el-table-column>
      <el-table-column label="版本号" min-width="60px" align="left">
        <template v-slot="{row}">
          <span>{{ row.version }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否挂起" min-width="70px" align="left">
        <template v-slot="{row}">
          <el-tag v-if="row.suspended === true">是</el-tag>
          <el-tag v-else-if="row.suspended === false">否</el-tag>
          <el-tag v-else>未知</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="租户" min-width="60px" align="left">
        <template v-slot="{row}">
          <span>{{ row.tenantId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="140px" align="left">
        <template v-slot="{row}">
          <span>{{ row.createTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" fixed="right" width="160px" class-name="small-padding fixed-width">
        <template v-slot="{row,$index}">
          <el-button size="mini" type="info" icon="el-icon-document" @click="handleDetail(row, $index)">详情</el-button>
          <el-dropdown style="margin-left: 10px;" @command="handleClick($event, row, $index)">
            <el-button size="mini" type="primary">更多
              <i class="el-icon-arrow-down el-icon--right" />
            </el-button>
            <el-dropdown-menu>
              <el-dropdown-item v-permission="permission.del" command="del"><i class="el-icon-delete"> 删除</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.suspend" command="suspend"><i class="el-icon-video-pause"> 挂起</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.active" command="active"><i class="el-icon-video-play"> 激活</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.config" command="config"><i class="el-icon-setting"> 配置</i></el-dropdown-item>
              <el-dropdown-item v-permission="permission.config" command="copy"><i class="el-icon-setting"> 拷贝</i></el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格分页 -->
    <pagination :total="total" :page.sync="listQuery.pageNum" :limit.sync="listQuery.pageSize" @pagination="handleInit" />

    <!-- 图片预览页面 -->
    <el-dialog title="流程图" :visible.sync="visible" :close-on-click-modal="false" @close="handleClose">
      <el-form ref="dataForm" label-position="right" label-width="100px" style="height: 450px;">
        <el-tabs style="height: 450px;">
          <el-tab-pane label="流程信息">
            <el-image
              style="margin: 10px;"
              :src="imageUrl"
            />
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-dialog>

    <!-- 文件上传 -->
    <el-dialog title="部署流程" :visible.sync="upload" :close-on-click-modal="false" @close="handleClose">
      <el-form>
        <el-upload
          ref="uploadRef"
          class="upload-demo"
          action="/api/flow/definition/deploy"
          drag
          :before-upload="handleBeforeUpload"
          :http-request="handleUpload"
          :on-success="handleSuccess"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          <div slot="tip" class="el-upload__tip">只能上传Xml文件</div>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button icon="el-icon-close" @click="upload = false">
          取消
        </el-button>
      </div>
    </el-dialog>

    <!--配置页面-->
    <definition-config ref="dataFormConfig" :params="config" />
  </div>
</template>

<script>
import { handleUpload } from '@/api/ft'
import {
  handleGetPageList,
  handleSave,
  handleDelete,
  handleSuspend,
  handleActive,
  handleDiagram,
  handleXml,
  handleCopy
} from './api'
import permission from '@/directive/permission/index' // 权限判断指令
// import checkPermission from '@/utils/permission' // 权限判断函数
import waves from '@/directive/waves' // waves directive
// import { parseTime } from '@/utils'
import Pagination from '@/components/Pagination' //
import DefinitionConfig from './config.vue'
import FlowProcKey from '@/views/flow/components/ProcessKey/index.vue'

export default {
  // 当前页面名称（组件）
  name: 'FlowDefinition',
  // 引用组件
  components: { FlowProcKey, Pagination, DefinitionConfig },
  directives: { permission, waves },
  filters: {},
  data() {
    return {
      // 列表table的key
      tableKey: 0,
      // 遮罩层
      loading: true,
      // table数据对象
      list: [],
      // 总条数
      total: 0,
      // table条件查询对象
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        // sort: '+id',
        param: {
          id: undefined,
          key: undefined,
          name: undefined
        }
      },
      // 表单数据对象
      formData: {},
      // 是否显示弹出层
      visible: false,
      // 弹出层状态值（新增和修改共用同一个表单页面）
      state: '',
      // 弹出层标题
      title: {
        update: '修改',
        create: '新增',
        detail: '详情'
      },
      // 权限标识
      permission: {
        add: ['flow:def:add'],
        del: ['flow:def:del'],
        suspend: ['flow:def:suspend'],
        active: ['flow:def:active'],
        config: ['flow:def:config']
      },
      // 表单校验规则
      rules: {
        appName: [{ required: true, message: '所属应用不能为空', trigger: 'change' }],
        scope: [{ required: true, message: '授权范围不能为空', trigger: 'change' }],
        authorizedGrantTypes: [{ required: true, message: '授权类型不能为空', trigger: 'change' }],
        accessTokenValidity: [{ required: true, message: '访问令牌超时时间不能为空', trigger: 'change' }],
        refreshTokenValidity: [{ required: true, message: '刷新令牌不能为空', trigger: 'change' }],
        autoapprove: [{ required: true, message: '是否自动审核不能为空', trigger: 'change' }]
      },
      imageUrl: undefined,
      upload: false,
      config: {
        visible: false,
        processDefId: ''
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    this.handleInit()
    this.handleRestFormData()
  },
  mounted() {},
  methods: {
    // 查询table数据对象
    handleInit() {
      this.loading = true
      handleGetPageList(this.listQuery).then(res => {
        this.list = res.data
        if (res.total) {
          this.total = Number(res.total)
        }
        this.loading = false
      })
    },
    // 条件查询table数据
    handleFilterQuery() {
      this.listQuery.pageNum = 1
      this.handleInit()
    },
    // 重置table查询条件
    handleRestQuery() {
      this.$refs.queryForm.resetFields()
    },
    // 重置表单
    handleRestFormData() {
      this.formData = {
        id: undefined,
        appName: undefined,
        appSecret: undefined,
        clientId: undefined,
        scope: 'all',
        authorizedGrantTypes: undefined,
        webServerRedirectUri: undefined,
        accessTokenValidity: undefined,
        refreshTokenValidity: undefined,
        additionalInformation: undefined,
        autoapprove: 'true',
        status: 'Y',
        remark: ''
      }
    },
    // 更多点击操作项
    handleClick(item, row, index) {
      // 删除
      if (item === 'del') {
        this.handleDelete(row, index)
      }
      // 挂起
      if (item === 'suspend') {
        this.handleSuspend(row, index)
      }
      // 激活
      if (item === 'active') {
        this.handleActive(row, index)
      }
      // 配置
      if (item === 'config') {
        this.handleConfig(row, index)
      }
      // 拷贝
      if (item === 'copy') {
        this.handleCopy(row, index)
      }
    },
    // 新增
    handleCreate() {
      this.state = 'create'
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 上传前
    handleBeforeUpload(file) {
      const isXml = file.type === 'text/xml' || file.type === 'text/xml'
      if (!isXml) {
        this.$message.error('只能上传 Xml 文件!')
      }
      return isXml
    },
    // 上传
    handleUpload(options) {
      const formData = new FormData()
      formData.append('file', options.file)
      handleUpload(options.action, formData).then((res) => {
        //  刷新table
        this.handleFilterQuery()
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success',
          duration: 4000
        })
        // 清空上传列表
        this.$refs.uploadRef.clearFiles()
        this.upload = false
      })
    },
    // 上传成功
    handleSuccess() {
      console.log('上传成功了')
      // 清空上传列表
      this.$refs.uploadRef.clearFiles()
    },
    // 详情
    handleDetail(row) {
      this.handleDiagram(row)
    },
    // 删除
    handleDelete(row, index) {
      this.$confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 显示加载遮罩
        const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
        handleDelete({ deploymentId: row.deploymentId }).then((res) => {
          loading.close()
          //  刷新table
          this.handleFilterQuery()
          this.$message({
            showClose: true,
            message: res.msg,
            type: 'success',
            duration: 4000
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 挂起
    handleSuspend(row, index) {
      const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
      handleSuspend({ processDefId: row.id }).then((res) => {
        loading.close()
        //  刷新table
        this.handleFilterQuery()
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success',
          duration: 4000
        })
      })
    },
    // 激活
    handleActive(row, index) {
      // 显示加载遮罩
      const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
      handleActive({ processDefId: row.id }).then((res) => {
        loading.close()
        //  刷新table
        this.handleFilterQuery()
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success',
          duration: 4000
        })
      })
    },
    // 配置
    handleConfig(row, index) {
      this.config.processDefId = row.id
      this.config.visible = true
      this.$nextTick(() => {
        this.$refs['dataFormConfig'].handleInit()
      })
    },
    // 拷贝
    handleCopy(row, index) {
      // 显示加载遮罩
      const loading = this.$loading({ lock: true, text: '处理中...', body: true, fullscreen: false, background: 'rgba(0, 0, 0, 0.05)' })
      handleCopy({ procDefId: row.id }).then((res) => {
        loading.close()
        //  刷新table
        this.handleFilterQuery()
        this.$message({
          showClose: true,
          message: res.msg,
          type: 'success',
          duration: 4000
        })
      })
    },
    // 表单提交
    handleSubmitFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.formData.authorizedGrantTypes = this.formData.authorizedGrantTypes.join(',')
          handleSave(this.formData).then((res) => {
            this.handleRestFormData()
            //  刷新table
            this.handleFilterQuery()
            this.visible = false
            this.$message({
              showClose: true,
              message: res.msg,
              type: 'success',
              duration: 4000
            })
          })
        }
      })
    },
    // 关闭弹出层
    handleClose() {
      this.handleRestFormData()
      this.visible = false
    },
    // 查看流程图
    async handleDiagram(row) {
      const res = await handleDiagram(row.id)
      const blob = new Blob([res])
      this.imageUrl = URL.createObjectURL(blob)
      this.visible = true
    },
    // 下载流程xml
    async handleXml(row) {
      const res = await handleXml(row.id)
      const blob = new Blob([res])
      const link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = row.resource
      document.body.appendChild(link)
      link.click()
      link.remove()
    }
  }
}
</script>
